package jude.java.money.batch.task;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jude.java.money.batch.Definition;
import jude.java.money.batch.Parameter;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.DefaultHttpParams;

/**
 * @deprecated 失败, 未完成
 * */
public class IXSubmiter extends BatchTask<String[]> {

	private static final String LOGIN_URL = "https://manage.ixwebhosting.com/index.php/login.dspFrmLogin";
	private static final String LOGIN2_URL = "https://manage.ixwebhosting.com/index.php";
	private static final String HOME_URL = "https://manage.ixwebhosting.com/index.php/cpanelcustomeraccount.dspmain";
	private static final String MANAGER_URL = "https://manage.ixwebhosting.com/index.php";
	private static final String DOMAIN_LIST_URL = "https://cp11.ixwebhosting.com/psoft/servlet/psoft.hsphere.CP/C330631/586526_0/psoft.hsphere.CP?template_name=domain/list.html";
//	private static final String SUBMIT_URL = "https://cp11.ixwebhosting.com/psoft/servlet/psoft.hsphere.CP/C330631/586526_0/psoft.hsphere.CP";
	
	public IXSubmiter(Parameter<String[]> p) {
		super(p);
		assertType(Definition.TYPE_WORDPRESS);
	}
	
	@Override
	protected String getLabel() {
		return "IXS";
	}
	
	@Override
	public void run() {
		try {
			HttpClient client = getHttpClient();
			String usr = P.PARAMS[0];
			String pwd = P.PARAMS[1];
			PostMethod post = getLoginMethod(usr, pwd);
			int status = client.executeMethod(post);
			if (status != 302) {
				System.out.println(status + " Login");
				return;
			}
			Header h = post.getResponseHeader("location");
			if (h == null)
				return;
			System.out.println(h.getValue());
			post.releaseConnection();
			
			visit(client, h.getValue());
			
			DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);

			post = getManageMethod();
			status = client.executeMethod(post);
			if (status != 302) {
				System.out.println(status + " manage");
				return;
			}
			h = post.getResponseHeader("location");
			if (h == null)
				return;
			System.out.println(h.getValue());
			post.releaseConnection();
			
			visit(client, h.getValue());
			
			GetMethod get = getListMethod();
			status = client.executeMethod(get);
			if (status != 200) {
				System.out.println(status + " List");
				return;
			}
			
			List<String> current = getCurrentDomains(get.getResponseBodyAsStream());
			System.out.println(current);
			get.releaseConnection();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void execute(String site, String url, int group, int index)
			throws IOException {
	}


	private PostMethod getLoginMethod(String usr, String pwd) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new NameValuePair("fuseaction", "login.actValidateLogin"));
		params.add(new NameValuePair("targetcircuit", "cpanelcustomeraccount"));
		params.add(new NameValuePair("targetfuse", "dspmain"));
		params.add(new NameValuePair("targetattributes", ""));
		params.add(new NameValuePair("logincircuit", "cpanelcustomeraccount"));
		params.add(new NameValuePair("b_use_ssl_session", "1"));
		params.add(new NameValuePair("email", usr));
		params.add(new NameValuePair("password", pwd));
		params.add(new NameValuePair("submit", "Login to Your Account"));
		params.add(new NameValuePair("rememberme", "1"));
		params.add(new NameValuePair("submit", "Login to Your Account"));
		PostMethod method = getPostMethod(LOGIN2_URL, params);
		method.addRequestHeader("Referer", LOGIN_URL);
		method.addRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; CIBA)");
		return method;
	}
	
	private PostMethod getManageMethod() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new NameValuePair("fuseaction", "cpanelcustomeraccount.actLoginHsphere"));
		params.add(new NameValuePair("hsphere_accountid", "586526"));
		PostMethod method = getPostMethod(MANAGER_URL, params);
		method.addRequestHeader("Referer", HOME_URL);
		method.addRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; CIBA)");
		return method;
	}
	
	private GetMethod getListMethod() {
		GetMethod method = new GetMethod(DOMAIN_LIST_URL);
		method.addRequestHeader("Referer", HOME_URL);
		return method;
	}
	
	private String getResponse(InputStream in) {
		try {
			InputStreamReader reader = new InputStreamReader(in);
			char[] buff = new char[1024];
			StringBuilder sb = new StringBuilder();
			int n = 0;
			while ((n = reader.read(buff)) != -1) {
				sb.append(buff, 0, n);
			}
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private List<String> getCurrentDomains(InputStream in) {
		List<String> domains = new ArrayList<String>();
		String resp = getResponse(in);
		if (resp == null) {
			return domains;
		}
		System.out.println(resp);
		Pattern p = Pattern.compile("<a href=\"http://([\\w._-]{4,30})\" target=\"preview\" title=\"Click to open site\">");
		Matcher m = p.matcher(resp);
		int n = 0;
		while(m.find(n)) {
			String domain = m.group(1).toLowerCase();
			domains.add(domain);
		}
		return domains;
	}
	
	private void visit(HttpClient client, String url) {
		try {
			GetMethod get = new GetMethod(url);
			get.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.RFC_2109);
//			get.addRequestHeader("Referer", HOME_URL);
			get.addRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; CIBA)");
			get.setFollowRedirects(false);
			int status = client.executeMethod(get);
			if (status == 302) {
				Header h = get.getResponseHeader("location");
				System.out.println(h.getValue());
//				get.releaseConnection();
				if (h == null || url.equals(h.getValue())) {
					System.out.println("same url");
					return;
				}
				visit(client, h.getValue());
			} else if (status != 200) {
				System.out.println(status + " visit");
			}
			get.releaseConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
